package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/sessions")
public class SessionController {
    @Autowired
    private IUserService service;

    @PostMapping
    public Object login(Model model, User user){
        JSONResult result = new JSONResult();
        try {
            User info = service.login(user);
            result.setObj(info);
            UserContext.setCurrentUser(info);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }
    @DeleteMapping
    public void Logout(HttpSession session, HttpServletResponse resp){
        session.invalidate();
        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
}
